<?php
/**
 * Created by PhpStorm.
 * User: osxfal
 * Date: 2019/2/23
 * Time: 下午6:37
 */


namespace app\index\controller;
use think\Controller;
use think\cache\driver\Redis;

/* 用户管理*/
class User extends Controller{




    /*用户列表
        表名： go_member
        二级渠道需要的表： go_admin
        外键 home_agent => uid

        ID	用户名	手机	来源	二级渠道	注册时间	实名情况	真实姓名	性别	民族	身份证号	所在城市	芝麻分
    */

    //判断用户是否登录
    /*public function __construct()
    {
        parent::__construct();
        if(empty(session('user')))
        {
            $this->error('对不起,您还没有登录!请先登录!','index/login');

        }

    }*/

    public function userList(){

        /*       查询 条件  */
        $data = [];
        $data['m.username'] = input('get.username');
        $data['m.typeid'] = input('get.typeid');
        $stime = input('get.stime');
        $etime = input('get.etime');
        $data['m.mobile'] = input('get.mobile');
        $data['m.is_name'] = input('get.is_name');  //是否实名  接收 数字  1.是。 2.否 . 3.全部
        $page = input('get.page');  //页码
        $lines = input('get.lines');    //每页行数



        if(empty($page)){
            $page = 1;
        }

        if(empty($lines)){
            $lines = 20;
        }


        $where=[];
        if($data['m.is_name']!=3){
            $where['m.is_name'] = $data['m.is_name'] ;
        }

        if($data['m.typeid']){
            $where['m.typeid'] = $data['m.typeid'];
        }

        if($data['m.username']){ //用户名搜索
            $where['m.username'] = ['LIKE','%'. $data['m.username'] . '%'];
        }

        if($data['m.mobile']){ //用户名搜索
            $where['m.mobile'] = $data['m.mobile'];
        }

        if($stime && $etime){
            $stime = strtotime($stime);
            $etime = strtotime($etime);

            $where['time'] = ['BETWEEN',[$stime,$etime]];
        }


        $limit = ($page - 1) * $lines . ',' . $lines;    //分页


        $field = 'm.uid,m.username,m.mobile,m.from,a.username as d_name,m.time,
                    m.is_name,m.real_name,m.sex,m.mingzu,m.card_no,m.city,m.zhimafen'; //初始化  字段

        $join = [
            ['go_admin a','m.diamond=a.uid','LEFT'],
        ];


        if($where){

            $res = db('member')
                ->alias('m')
                ->field($field)
                ->join($join)
                ->where($where)
                ->limit($limit)
                ->select();


            $total = db('member')->alias('m')->field('COUNT(uid) as t')->where($where)->find();
        }else{
            $res = db('member')
                ->alias('m')
                ->field($field)
                ->join($join)
                ->limit($limit)
                ->select();
            $total = db('member')->field('COUNT(uid) as t')->find();

        }

        //时间戳 转为 日期
        foreach ($res as $k=>&$v){
            if($v['time']){
                $v['time'] = date('Y-m-d H:i:s',$v['time']);
            }

        }//foreach

//        echo db('member')->getLastSql();die;
//        dump($res);die;

        //数据转化
//        foreach($res as $k=>&$v){

            //转化实名情况
//            if(!empty($v['is_name']) || $v['is_name']==0){
//                switch($v['is_name']){
//                    case 0:
//                        $v['is_name'] = '<font color="red">未激活</font>';
//                        break;
//
//                    case 1:
//                        $v['is_name'] = '已实名';
//                        break;
//
//                    case 2:
//                        $v['is_name'] = '审核中';
//                        break;
//
//                    default:
//                        $v['is_name'] = '未知状态';
//                        break;
//                }//switch
//            }


            //其它认证方式
//            if(!empty($v['othercode']) || $v['othercode']==0){
//                switch($v['othercode']){
//
//                    case 1:
//                        $v['othercode'] = '认证通过';
//                        break;
//
//                    default:
//                        $v['othercode'] = '未通过认证';
//                        break;
//                }//switch
//            }


            //注册来源
//            if(!empty($v['typeid']) || $v['typeid']==0){
//                switch($v['typeid']){
//                    case 0:
//                        $v['typeid'] = '电脑端';
//                        break;
//
//                    case 1:
//                        $v['typeid'] = '手机端';
//                        break;
//
//                    case 2:
//                        $v['typeid'] = '微信关注';
//                        break;
//
//                    case 3:
//                        $v['typeid'] = '快捷登录QQ';
//                        break;
//
//                    case 4:
//                        $v['typeid'] = '微信快捷';
//                        break;
//
//                    default:
//                        $v['typeid'] = '未知来源';
//                        break;
//                }//switch
//            }//if


//        }//foreach

        $ret = [];
        if($res && $res!==false){
            $ret['rows'] = $res;
            $ret['total'] = $total['t'];
            $ret['result'] = 1;
            $ret['tips'] = '查询成功！';


        }
        elseif(empty($res)){
            $ret['rows'] = [];
            $ret['total'] = 0;
            $ret['result'] = 1;
            $ret['tips'] = '查询成功！并没有符合条件的数据！';
        }
        else{
            $ret['rows'] = [];
            $ret['total'] = 0;
            $ret['result'] = 2;
            $ret['tips'] = '查询失败，请稍后再试~~';

        }



//        //平台下拉列表  typeid
//        $platform_list = db('member')->field('DISTINCT typeid')->select();
//        foreach($platform_list as &$v){
//            switch ($v['typeid']){
//                case 0:  $v['pname'] = 'PC';break;
//                case 1:  $v['pname'] = '手机';break;
//                case 2:  $v['pname'] = '微信';break;
//                case 3:  $v['pname'] = 'QQ快捷';break;
//                case 4:  $v['pname'] = '微信快捷';break;
//            }
//        }
//
//
//
//        //实名 下拉列表  is_name
//        $is_name_list = db('member')->field('DISTINCT is_name')->select();
//        foreach($is_name_list as &$v){
//            switch ($v['is_name']){
//                case 0:  $v['stat'] = '未实名';break;
//                case 1:  $v['stat'] = '已实名';break;
//                case 2:  $v['stat'] = '审核中';break;
//
//            }
//        }


        $ret = json_encode($ret,JSON_UNESCAPED_UNICODE);
        exit($ret);


    }//func  userlist


    /*修改用户信息  其实只是审核通过而已  */
    public function user_real_name_verify(){

        //头像传输  字段 img
        $uid = input('post.uid');


        /*$username = input('post.username');//用户名
        $mobile = input('post.mobile');//手机
        $from = input('post.from'); //来源
        $real_name = input('post.real_name');
        $sex = input('post.sex');
        $mingzu = input('post.mingzu');  //民族

        $card_no = input('post.card_no'); //身份证
        $date = input('post.date');  //生日
        $city = input('post.city');  //所在城市
        $zhimafen = input('post.zhimafen'); //芝麻粉*/


        $is_name = input('post.is_name'); //实名审核情况

        $res = db('member')->where(['uid'=>$uid])->insert(['is_name'=>$is_name]);



        $arr = [];

        if($res){ //插入成功

            $arr['result'] = 1;
            $arr['tips'] = '恭喜！ 用户信息更新成功~~';

            $arr = json_encode($arr,320);
            exit($arr);
        }else{
            $arr['result'] = 2;
            $arr['tips'] = '很遗憾， 未能更新用户信息~ 稍后再试';

            $arr = json_encode($arr,320);
            exit($arr);

        }


    }//func  user_real_name_verify



    /*修改用户信息  数据来源 app 端
        go_member
    */
    public function user_edit(){

        //参数接收
        $where = []; //定位
        $data = []; //要修改的参数



        //头像传输  字段 img
        $uid = input('post.uid');
        if($uid){

            //查看  is_name_time 是否有值， 有就代表已经传过一次
            $check_name_time = db('member')->field('is_name_time')->where(['uid'=>$uid])->find();

            $where['uid'] = trim($uid);


            $data['username'] = input('post.username');//用户名
            $data['username'] = trim($data['username']);


            $data['real_name'] = input('post.real_name');  //真实姓名

            //当用户填写姓名 且 原有数据（只有手机 和 uid）的实名时间为null , 就添加 实名时间  is_name_time
            if(!empty($data['real_name']) && $check_name_time['is_name_time'] === null){
                $data['is_name_time'] = strtotime(date('Y-m-d H:i:s',time()));
            }
            $data['sex'] = input('post.sex'); //性别
            // $data['mingzu'] = input('post.mingzu');  //民族

            $data['card_no'] = input('post.card_no'); //身份证
            $data['date'] = input('post.date');  //生日
            $data['city']= input('post.city/a');  //所在城市
            $data['zhimafen'] = input('post.zhimafen'); //芝麻粉


            if(is_array($data['city'])){ //如果是数组， 改为 string
                $data['city'] = implode(',',$data['city']);
            }

            //验证
            if(!isset($data['username'])) unset($data['username']);
            if(!isset($data['real_name'])) unset($data['real_name']);
            if(!isset($data['sex'])) unset($data['sex']);
            if(!isset($data['card_no'])) unset($data['card_no']);
            if(!isset($data['date'])) unset($data['date']);
            if(!isset($data['city'])) unset($data['city']);
            if(!isset($data['zhimafen'])) unset($data['zhimafen']);


            //更新到数据库
            $res = db('member')->where($where)->update($data);
            $arr = [];

            if($res!==false){ //插入成功

                $arr['result'] = 1;
                $arr['tips'] = '恭喜！ 用户信息更新成功~~';

                $arr = json_encode($arr,320);
                exit($arr);
            }else{
                $arr['result'] = 2;
                $arr['tips'] = '很遗憾， 未能更新用户信息~ 稍后再试';

                $arr = json_encode($arr,320);
                exit($arr);

            }
        }
        else{
            $arr['result'] = 2;
            $arr['tips'] = '用户id丢失，无法定位~~';

            $arr = json_encode($arr,320);
            exit($arr);
        }



    }//func  user_real_name_verify





    /* 用户数据导出  go_member*/
    public function export(){

        /*import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Worksheet.Drawing");
        import("Org.Util.PHPExcel.Writer.Excel2007");
        import("Org.Util.PHPExcel.Style.NumberFormat");
        import("Org.Util.PHPExcel.Style.Alignment");
        import("Org.Util.PHPExcel.Style.Color");
        import("Org.Util.PHPExcel.Style.Border");*/

        $cached = new Redis();
        $data = [];
        if($cached->get('clientData')){//有缓存就用缓存
            $data = $cached->get('clientData');
            $data = json_decode($data,true);
        }
        else{
            $field = 'm.uid,m.username,m.mobile,m.from,a.username as d_name,m.time,m.is_name,
                    m.real_name,m.sex,m.mingzu,m.card_no,m.city,m.zhimafen'; //初始化  字段

            $join = [
                ['go_admin a','m.home_agent=a.uid','LEFT'],
            ];


            $data = db('member')
                ->alias('m')
                ->field($field)
                ->join($join)
                ->select();

            //时间戳 转为 日期
            foreach ($data as $k=>&$v){
                if($v['time']){
                    $v['time'] = date('Y-m-d H:i:s',$v['time']);
                }

            }//foreach
        }

//        exit($data);die;


        $objPHPExcel = new \PHPExcel();
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);

        //设置全局单元格水平居中
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置全局单元格垂直居中
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

        for($i='A';$i<='Y';$i++){  //通过循环修改列宽
            $objPHPExcel->getActiveSheet()->getColumnDimension($i)->setWidth(18);
        }

        $objActSheet = $objPHPExcel->getActiveSheet();

        //设置excel表头
        $objActSheet ->setCellValue('A1', 'ID');
        $objActSheet ->setCellValue('B1', '用户名');
        $objActSheet ->setCellValue('C1', '手机');
        $objActSheet ->setCellValue('D1', "来源");
        $objActSheet ->setCellValue('E1', "二级渠道");
        $objActSheet ->setCellValue('F1', "注册时间");
        $objActSheet ->setCellValue('G1', "实名情况");
        $objActSheet ->setCellValue('H1', '真实姓名');
        $objActSheet ->setCellValue('I1', '性别');
        $objActSheet ->setCellValue('J1', "民族");
        $objActSheet ->setCellValue('K1', '身份证号');
        $objActSheet ->setCellValue('L1', "所在城市");
        $objActSheet ->setCellValue('M1', "批芝麻分");

        //以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改
        $step = 1;
        foreach($data as $k => $v) {
            $step += 1;
            $objPHPExcel->setActiveSheetIndex(0);
            //Excel的第A列，uid是你查出数组的键值，下面以此类推
            $objActSheet->setCellValue('A' . $step, $v['uid']);
            $objActSheet->setCellValue('B' . $step, $v['username']);
            $objActSheet->setCellValue('C' . $step, $v['mobile']);
            $objActSheet->setCellValue('D' . $step, $v['from']);
            $objActSheet->setCellValue('E' . $step, $v['d_name']);
            $objActSheet->setCellValue('F' . $step, $v['time']);
            $objActSheet->setCellValue('G' . $step, $v['is_name']);
            $objActSheet->setCellValue('H' . $step, $v['real_name']);
            $objActSheet->setCellValue('I' . $step, $v['sex']);
            $objActSheet->setCellValue('J' . $step, $v['mingzu']);
            $objActSheet->setCellValue('K' . $step, $v['card_no']);
            $objActSheet ->setCellValue('L' . $step, $v['city']);
            $objActSheet ->setCellValue('M' . $step, $v['zhimafen']);

        }//end foreach

        $fileName = '用户信息表';
        $date = date("Y-m-d",time());
        $fileName .= "_{$date}.xls";

        $objPHPExcel->setActiveSheetIndex(0);//这一句一定要留，不然导出的都是乱码。。。
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');   //这是老版本的 使用2007 的
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;

    }//export user


    /* 用户注册 */
    public function user_reg($user_data){//用户注册
        /* 接收用户参数 */

        $username = input('post.username');
        $userpass = input('post.userpass');
        $msg_code = input('msg_code');

        //验证短信是否正确

        $check_code = new MessagesApi();


        if($check_code->check_verified_code($msg_code)){
            $msg = [];
            $where = [];
            $where['username'] = $username;
            $where['userpass'] = $userpass;

            //判断是否有该用户存在
            if(!$this->check_user_exist($username)){//没有就插入新用户
                $res = db('member')->insert($where);
                if($res){

                    
                    $msg['result'] = 1;
                    $msg['msg'] = '注册成功！';
                    $msg = json_encode($msg,320);
                    exit($msg);
                }else{
                    $msg['result'] = 2;
                    $msg['msg'] = '网络传输故障，请检查网络~';
                    $msg = json_encode($msg,320);
                    exit($msg);
                }

            }else{
                $msg = [];
                $msg['result'] = 2;
                $msg['msg'] = '该用户已存在';
                $msg = json_encode($msg,320);
                exit($msg);
            }
            
        }//if
    }//func user_reg

    /* 查是否重复名 */
    public function check_user_exist($username){

        $res = db('member')->where(['username'=>$username])->find();

        if(empty($res)){
            return false;
        }else{
            return true;
        }
    }


    //个人信息回显
    public function user_personal(){
        $uid = input('get.uid');

        $field = 'username,mobile,from,real_name,sex,mingzu,card_no,date,city,zhimafen,is_name';
        $res = db('member')->field($field)->where(['uid'=>$uid])->select();
        // dump($res);die;


        $msg = [];
        if(!empty($res)){
            /* foreach($res as &$v){
                
                switch ($v['sex']){
                    case 0:$v['sex'] = '保密';break;
                    case 1:$v['sex'] = '帅哥';break;
                    case 2:$v['sex'] = '美女';break;
                    default: $v['sex'] = '保密';break;
                }
            } */
            $msg['result'] = 1;
            $msg['tips'] = '查询成功!';
            $msg['rows'] = $res;
            exit(json_encode($msg,320));
        }else{
            $msg['result'] = 2;
            $msg['tips'] = '查询失败， 并无匹配数据!';
            $msg['rows'] = '';
            exit(json_encode($msg,320));
        }
    }



    /*用户删除*/
    public function user_del(){
        $uid = input('get.id');
        $res = db('member')->delete(['uid'=>$uid]);

        $msg = [];
        $msg['result'] = 1;
        $msg['tips'] = '用户删除成功!';
        exit(json_encode($msg,320));
    }


}